package io.terminus.lego.shinda.web.filter

import io.terminus.lego.shinda.web.context.UserContext
import io.terminus.lego.shinda.web.controller.dto.UserDTO
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import javax.servlet.*
import javax.servlet.http.HttpServletRequest

/**
 * 用户信息上下文filter
 * 职能是将用户信息设置到上下文中，以便controller接口能方便的拿到用户信息
 * 注意一点：order在当前filter之前的filter是无法使用userContext的，毕竟还没设置是不是。
 * @author wangmeng
 * @date 2018/4/26
 */
@Component
class UserContextFilter : Filter {

    val logger = LoggerFactory.getLogger(javaClass)

    override fun destroy() {
        logger.debug("BindContextFilter destory")
    }

    override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
        try {
            //从Session中获取用户信息，设置到上下文中
            val session = (request as HttpServletRequest).session
            val user = session.getAttribute(UserContext.SESSION_KEY)
            if (user != null) {
                UserContext.setCurrentUser(user as UserDTO)
            }
            chain.doFilter(request, response)
        } finally {
            //清空上下文，防止线程复用时出现脏数据
            UserContext.clear()
        }
    }

    override fun init(filterConfig: FilterConfig?) {
        logger.debug("BindContextFilter init")
    }

}